using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace XLFrame.NodeEditor
{
    /// <summary>
    /// 继承自这个类创建的ScriptableObject若干个数据可合并成一个整体数据，主要保存配置信息(不支持字典)
    /// </summary>
    public class SerializedCollectionDataBase : ScriptableObject
    {
        [SerializeField, HideInInspector]
        private List<SerializedDataBase> serializedDataBaseData;
        public List<SerializedDataBase> SerializedDataBase => serializedDataBaseData;

#if UNITY_EDITOR
        /// <summary>
        /// 创建一个数据对象,支持保存到此类内和移除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T CreateData<T>() where T : SerializedDataBase
        {
            var obj = CreateInstance<T>();
            obj.name = $"{typeof(T).Name}[{Guid.NewGuid()}]";
            obj.SetParent(this);
            serializedDataBaseData.Add(obj);
            obj.SaveData();
            return obj;
        }
#endif
    }

    /// <summary>
    /// SerializedCollectionDataBase 支持的内部数据对象,可自行保存
    /// </summary>
    public class SerializedDataBase : ScriptableObject
    {
        [SerializeField, HideInInspector]
        private SerializedCollectionDataBase ParentObject;

        public void SetParent(SerializedCollectionDataBase parent)
        {
            ParentObject = parent;
        }

#if UNITY_EDITOR
        public void SaveData()
        {
            AssetDatabase.AddObjectToAsset(this, ParentObject);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }

        public void RemoveData()
        {
            AssetDatabase.RemoveObjectFromAsset(this);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            ParentObject.SerializedDataBase.Remove(this);
        }
#endif
    }
}

